package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /*点赞某篇博客，点赞的时候会判断这篇博客是否被该用户点过赞*/
    @Override
    public Result likeBlog(Long id) {
        /*1.获取用户id,并判断用户id是否存在*/
        Long userId = UserHolder.getUser().getId();
        if(userId==null){
            return null;
        }
        /*2.使用redis里面的sortedset，实现点赞排行榜，并且实现每个用户只能下一次单*/
        /*3.构建sortedset的key*/
        String key=RedisConstants.BLOG_LIKED_KEY+id;
        /*4.判断该用户id是否在这个sortedset集合里面*/
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score!=null){
            /*5.如果在sortedset集合里面，说明用户已经点赞，更新blog表里面的字段减一*/
            boolean flag1 = update().setSql("liked=liked-1").eq("id", id).update();
            if(flag1){
                /*6.将userId从sortedset集合里面移除*/
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }else {
            /*7.如果用户id没有在sortedset集合里面*/
            /*8.更新blog数据表，字段加一*/
            boolean flag2 = update().setSql("liked=liked+1").eq("id", id).update();
            /*9.将userId添加到sortedset集合里面*/
            if(flag2){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    /*根据博客id查询某篇文章的top5点赞用户*/
    /*这里用到了java8的新特性，stream流*/
    @Override
    public Result likesByBlogId(Long id) {
        /*1.构造redis里面sortedset里面的key值*/
        String key=RedisConstants.BLOG_LIKED_KEY+id;
        /*2.根据key值拿到top5的点赞用户*/
        Set<String> rangeTop5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(rangeTop5==null || rangeTop5.isEmpty()){
            return null;
        }
        /*3.解析用户，根据用户id解析出用户的信息*/
        List<Long> userIds = rangeTop5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join("", userIds);
        /*根据用户id查询用户*/
        List<UserDTO> userDTOS = userService.query().in("id", userIds)
                .last("order by field(id," + idStr + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        /*返回信息*/
        return Result.ok(userDTOS);
    }

    /*根据blog的id获取blog的详细信息*/
    @Override
    public Result queryBlogById(Long id) {
        /*1.根据blog的id查询blog信息*/
        Blog blog = baseMapper.selectById(id);
        /*2.判断博客是否为空*/
        if(blog==null){
            return Result.fail("博客不存在");
        }
        /*3.查询博客所对应的用户信息*/
        queryBlogUser(blog);
        /*4.查询该博客是否被点赞*/
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /*查询博客相关的用户*/
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
    }

    /*查询该篇博客是否被当前用户点赞*/
    private void isBlogLiked(Blog blog) {
        /*1.获取当前登录用户，并判断用户是否为空*/
        Long userId = UserHolder.getUser().getId();
        if(userId==null){
            return;
        }
        /*2.构造redis里面sortedset的key*/
        String key=RedisConstants.BLOG_LIKED_KEY+blog.getId();
        /*3.判断该用户是否点赞*/
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    /*用户保存博客信息*/
    /*博客发送成功之后，需要使用feed流实现博客推送到粉丝的收件箱里面*/
    @Override
    public Result saveBlog(Blog blog) {
        /*1.获取当前登录用户信息*/
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        save(blog);
        /*2.把当前博客信息推送到粉丝收件箱里面*/
        /*获取当前用户的所有粉丝id*/
        List<Follow> follows = followService.query().eq("user_id", userId).list();
        follows.stream()
                .forEach(follow -> {
                    Long followUserId = follow.getFollowUserId();
                    String redisKey=RedisConstants.FEED_KEY+followUserId;
                    stringRedisTemplate.opsForZSet().add(redisKey, blog.getId().toString(), System.currentTimeMillis());
                });
        return Result.ok(blog.getId());
    }


    /*滚动分页查询*/
    /*
     * 参数说明
     * 1.max表示上一次查询的最小时间搓，也是这一次查询的最大时间搓
     * 2.offset就是偏移量
     * */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        /*1.获取当前用户*/
        Long userId = UserHolder.getUser().getId();
        /*2.查询收件箱    zrevrangebyscore key max min limit offset count  */
        String key=RedisConstants.FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 4);
        if(typedTuples==null || typedTuples.isEmpty()){
            return Result.ok();
        }
        /*3.解析数据，blogId,minTime(时间搓),offset(偏移量)*/
        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            /*获取id*/
            String idStr = typedTuple.getValue();
            ids.add(Long.valueOf(idStr));
            long time= typedTuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else {
                /*获取分数也就是时间搓*/
                minTime =time;
                os=1;
            }
        }
        /*4.根据blog的Id查询blog*/
        String idStr=StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            /*查询blog有关的用户*/
            queryBlogUser(blog);
            /*查询blog是否被点赞*/
            isBlogLiked(blog);
        }
        /*5.封装并返回*/
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);

    }

}
